import * as THREE from 'three'
import { gsap } from 'gsap'
import { setCityMaterial, getSurroundLine } from '../utils/material'
import { forMaterial } from '../utils'
import { FBXLoader } from 'three/examples/jsm/Addons.js'
import { Fly, Radar, Wall } from '../effect'

export default function useCity() {
  const time = {
    value: 0
  }
  const dt = 1 / 60
  gsap.timeline({
    repeat: -1,
    yoyo: true,
    repeatDelay: dt,
    onUpdate() {
      time.value += dt
    }
  })
  const CityGroup = new THREE.Group()
  const loader = new FBXLoader()
  // 需要做城市效果的mesh
  const cityArray = ['CITY_UNTRIANGULATED']
  const floorArray = ['LANDMASS']
  loader.load('./source/model/shanghai.FBX', (obj: THREE.Group) => {
    CityGroup.add(obj);
    obj.traverse((child) => {
      // 城市效果
      if (cityArray.includes(child.name)) {
        // 设置建筑材质
        setCityMaterial(child, time)
        // 获取并且添加包围线条效
        const lineMesh = getSurroundLine(child, time);
        CityGroup.add(lineMesh);
      }
      if (floorArray.includes(child.name)) {
        // 设置地板材质
        setFloor(child)
      }
    });
  });

  const effectGroup = getEffect(time);
  CityGroup.add(effectGroup);

  return { city: CityGroup };
}

// 设置飞线、扫描、光墙效果
const getEffect = (time: any) => {
  const radarData = [
    {
      position: {
        x: 666,
        y: 20,
        z: 0,
      },
      radius: 150,
      color: '#ff0000',
      opacity: 0.5,
      speed: 1,
    },
  ]
  const wallData = [
    {
      position: {
        x: -150,
        y: 30,
        z: 100,
      },
      speed: 0.5,
      color: '#efad35',
      opacity: 0.6,
      radius: 420,
      height: 120,
      renderOrder: 5,
    },
  ]
  const flyData = [
    {
      source: {
        x: -150,
        y: 15,
        z: 100,
      },
      target: {
        x: 666,
        y: 22,
        z: 0,
      },
      height: 300,
      range: 150,
      color: '#ff0000',
      speed: 1,
      size: 40,
    },
  ]
  const effectGroup = new THREE.Group()
  setTimeout(() => {
    // 加载扫描效果
    radarData.forEach((data) => {
      const mesh = Radar(data)
      mesh.material.uniforms.time = time
      effectGroup.add(mesh)
    })
    // 光墙
    wallData.forEach((data) => {
      const mesh = Wall(data)
      mesh.material.uniforms.time = time
      effectGroup.add(mesh)
    })
    // 飞线
    flyData.forEach((data) => {
      const mesh = Fly(data)
      mesh.material.uniforms.time = time
      mesh.renderOrder = 10
      effectGroup.add(mesh)
    })
    gsap.to(time, { value: 2 * Math.PI, duration: 5, repeat: -1});
  }, 1000)
  return effectGroup;
}

// 设置地板
const setFloor = (object: any) => {
  forMaterial(object.material, (material: any) => {
    material.color.setStyle('#040912')
  })
}
